package com.af.community.smart.business

import android.os.Bundle
import android.view.MotionEvent
import android.widget.TextView
import com.af.community.smart.base.*
import com.af.community.smart.model.FormData
import com.af.community.smart.model.HouseData
import com.af.community.smart.model.ResultData
import com.af.community.smart.share.Const
import com.af.community.smart.utils.*
import com.af.community.smart.utils.DialogHelper.showDateDialog
import com.af.community.smart.utils.DialogHelper.showItemDialog
import com.af.community.smart.utils.DialogHelper.showListDialog
import com.af.community.smart.view.createSelectView
import com.af.community.smart.view.createStableInputView
import com.af.community.smart.view.createVariableInputView
import com.af.community.smart.viewmodel.HouseViewModel
import com.baidu.mapapi.BDLocationHelper
import com.baidu.mapapi.map.*
import com.baidu.mapapi.model.LatLng
import com.baidu.mapapi.setMapStatusChangeListener
import com.jeremyliao.liveeventbus.LiveEventBus
import com.lzg.extend.jackson.JsonUtil
import kotlinx.android.synthetic.main.activity_house_add.*
import kotlinx.android.synthetic.main.include_layout_map.*
import org.jetbrains.anko.collections.forEachWithIndex
import org.jetbrains.anko.toast
import org.json.JSONObject
import org.koin.androidx.viewmodel.ext.android.getViewModel
import java.util.*
import kotlin.collections.ArrayList
import kotlin.collections.HashMap

class HouseAddActivity : BaseActivity() {

    private val list = ArrayList<FormData>()
    private val areaList = ArrayList<ResultData>()
    private val buildList = ArrayList<ResultData>()
    private lateinit var mLabel: String
    private lateinit var mValue: String
    private var mLat = ""
    private var mLng = ""
    private var mData: HouseData? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_house_add)
        initTitle(name = "保存")
        initData()
        initView()
        initMapView()
        initListener()
    }

    override fun getViewModel() = getViewModel<HouseViewModel>()

    override fun initTitle(title: String, name: String) {
        mLabel = intent.getStringExtra("label").orEmpty()
        mValue = intent.getStringExtra("value").orEmpty()
        // super.initTitle(if (mLabel.isEmpty()) "添加房屋" else mLabel, name)
        super.initTitle("添加房屋", name)
        mData = intent.getSerializableExtra("data") as HouseData?
    }

    private fun initData() {
        when (mValue) {
            "ht_zf" -> list.addAll(Const.listOne)
            "ht_czf" -> list.addAll(Const.listTwo)
            "ht_zjcs" -> list.addAll(Const.listThree)
            "ht_yldw" -> list.addAll(Const.listFour)
            "ht_xzdw" -> list.addAll(Const.listFive)
            "ht_xhhzz" -> list.addAll(Const.listSix)
            "ht_xjjzz" -> list.addAll(Const.listSeven)
            "ht_zacs" -> list.addAll(Const.listEight)
            "ht_aqsc" -> list.addAll(Const.listNine)
            "ht_xfaq" -> list.addAll(Const.listTen)
            "ht_xx" -> list.addAll(Const.listEleven)
            "ht_qy" -> list.addAll(Const.listTwelve)
            "ht_yhdw" -> list.addAll(Const.listThirteen)
            "ht_jrxt" -> list.addAll(Const.listFourteen)
            "ht_qtcs" -> list.addAll(Const.listFifteen)
            else -> list.addAll(Const.listFifteen)
        }

        list.forEach {
            if (it.contentKey == "gridName") {
                it.content = getString("gridName")
                it.secondValue = getString("gridId")
            } else {
                it.content = ""
                it.secondValue = ""
            }
        }

        if (mData != null) {
            mLat = mData?.lat.orEmpty()
            mLng = mData?.lng.orEmpty()

            val json = JsonUtil.getMapperInstance().writeValueAsString(mData)
            val obj = JSONObject(json)
            list.forEach {
                val value = obj.optString(it.contentKey)
                when (it.contentKey) {
                    "foundDate" -> it.content = value.toFormatString(eFormat = "yyyy-MM-dd")
                    "gridName", "village", "buildName" -> {
                        it.content = value
                        it.secondValue = obj.optString(it.secondKey)
                    }
                    else -> it.content = value
                }
            }
        }
    }

    private fun initView() {
        list.forEachWithIndex { position, data ->
            when (data.viewFlag) {
                "select" -> {
                    add_container.addView(
                        createSelectView(
                            isRequired = data.isRequired,
                            title = data.title,
                            hintText = data.hintText,
                            position = position,
                            action = data.action,
                            content = when (data.contentKey) {
                                "right", "prod", "security",
                                "establish", "volunteer" -> when (data.content) {
                                    "1" -> "是"
                                    "0" -> "否"
                                    else -> ""
                                }
                                else -> data.content
                            },
                            listener = { view, action, index ->
                                when (action) {
                                    "type_house" -> {
                                        showListDialog(
                                            "集体生活住房", "集体房", "出租房",
                                            "闲置房", "生产经营房", "其他"
                                        ) { _, hint ->
                                            list[index].content = hint
                                            view.text = hint
                                        }
                                    }
                                    "structure" -> {
                                        showListDialog(
                                            "钢结构", "钢筋混凝土结构", "混合结构",
                                            "砖木结构", "木结构", "简易棚", "其他"
                                        ) { _, hint ->
                                            list[index].content = hint
                                            view.text = hint
                                        }
                                    }
                                    "village" -> {
                                        if (areaList.isEmpty()) {
                                            getViewModel().getGridVillage(getString("gridId"))
                                                .bindLifeCycle(getLifecycleOwner())
                                                .subscribeByFinally(
                                                    event = getViewModel(),
                                                    onSuccess = { result ->
                                                        areaList.addItems(result)
                                                        if (areaList.isNotEmpty()) {
                                                            val items = ArrayList<String>()
                                                            areaList.mapTo(items) { it.title }
                                                            showItemDialog(
                                                                list[index].hintText,
                                                                items.indexOf(list[index].content),
                                                                items
                                                            ) { pos, hint ->
                                                                list[index].content = hint
                                                                list[index].secondValue = areaList[pos].type
                                                                view.text = hint

                                                                clearSelectValue(index + 1)
                                                            }
                                                        }
                                                    }
                                                )
                                        } else {
                                            val items = ArrayList<String>()
                                            areaList.mapTo(items) { it.title }
                                            showItemDialog(
                                                list[index].hintText,
                                                items.indexOf(list[index].content),
                                                items
                                            ) { pos, hint ->
                                                list[index].content = hint
                                                list[index].secondValue = areaList[pos].type
                                                view.text = hint

                                                clearSelectValue(index + 1)
                                            }
                                        }
                                    }
                                    "build" -> {
                                        val formData = list.first { it.contentKey == "village" }
                                        if (formData.secondValue.isEmpty()) toast("请选择村/小区")
                                        else {
                                            getViewModel().getGridBuilding(
                                                getString("gridId"),
                                                formData.secondValue
                                            )
                                                .bindLifeCycle(getLifecycleOwner())
                                                .subscribeByFinally(
                                                    event = getViewModel(),
                                                    onSuccess = { result ->
                                                        buildList.clear()
                                                        buildList.addItems(result)
                                                        if (buildList.isNotEmpty()) {
                                                            val items = ArrayList<String>()
                                                            buildList.mapTo(items) { it.title }
                                                            showItemDialog(
                                                                list[index].hintText,
                                                                items.indexOf(list[index].content),
                                                                items
                                                            ) { pos, hint ->
                                                                list[index].content = hint
                                                                list[index].secondValue = buildList[pos].type
                                                                view.text = hint
                                                            }
                                                        }
                                                    }
                                                )
                                        }
                                    }
                                    "time_register" -> {
                                        val calendar = Calendar.getInstance()
                                        val yearNow = calendar.get(Calendar.YEAR)
                                        showDateDialog(
                                            maxYearValue = yearNow,
                                            count = 3,
                                            title = "请选择登记日期",
                                            isAfterLimited = true,
                                            callback = { _, _, _, _, _, hint ->
                                                list[index].content = hint
                                                view.text = hint
                                            }
                                        )
                                    }
                                    "whether" -> {
                                        showListDialog("是", "否") { pos, hint ->
                                            list[index].content = (1 - pos).toString()
                                            view.text = hint
                                        }
                                    }
                                    "type_hospital" -> {
                                        showListDialog(
                                            "公办", "民办", "合资", "外资", "其他"
                                        ) { _, hint ->
                                            list[index].content = hint
                                            view.text = hint
                                        }
                                    }
                                    "hospital_kind" -> {
                                        showListDialog(
                                            "综合医院", "专科医院", "门诊", "其他"
                                        ) { _, hint ->
                                            list[index].content = hint
                                            view.text = hint
                                        }
                                    }
                                    "hospital_level" -> {
                                        val items = listOf(
                                            "三等特级", "三等甲级", "三等乙级", "三等丙级", "二等甲级", "二等乙级",
                                            "二等丙级", "一等甲级", "一等乙级", "一等丙级", "未评等级", "不详"
                                        )
                                        showItemDialog(
                                            list[index].hintText,
                                            items.indexOf(list[index].content),
                                            items
                                        ) { _, hint ->
                                            list[index].content = hint
                                            view.text = hint
                                        }
                                    }
                                    "admin_title" -> {
                                        showListDialog(
                                            "高级", "中级", "初级"
                                        ) { _, hint ->
                                            list[index].content = hint
                                            view.text = hint
                                        }
                                    }
                                    "time_fund" -> {
                                        val calendar = Calendar.getInstance()
                                        val yearNow = calendar.get(Calendar.YEAR)
                                        showDateDialog(
                                            maxYearValue = yearNow,
                                            count = 3,
                                            title = "请选择成立时间",
                                            callback = { _, _, _, _, _, hint ->
                                                list[index].content = hint
                                                view.text = hint
                                            }
                                        )
                                    }
                                    "type_world" -> {
                                        val items = listOf(
                                            "学术性社团", "行业性社团", "专业性社团", "联合性社团", "行业协会",
                                            "社区活动团队", "民办非企业单位", "基金会", "中介组织", "非营利机构",
                                            "农村专业经济协会", "其他"
                                        )
                                        showItemDialog(
                                            list[index].hintText,
                                            items.indexOf(list[index].content),
                                            items
                                        ) { _, hint ->
                                            list[index].content = hint
                                            view.text = hint
                                        }
                                    }
                                    "type_income" -> {
                                        showListDialog(
                                            "私营企业", "外商投资企业", "港澳台商投资企业", "股份合作企业",
                                            "民营科技企业", "个体工商户", "混合所有制经济组织"
                                        ) { _, hint ->
                                            list[index].content = hint
                                            view.text = hint
                                        }
                                    }
                                    "type_public" -> {
                                        val items = listOf(
                                            "流动人口聚集地", "宾馆与旅馆", "客运站", "歌舞娱乐场所", "棋牌室",
                                            "网吧", "集贸市场", "工矿区", "建筑工地", "废品收购站点", "其他"
                                        )
                                        showItemDialog(
                                            list[index].hintText,
                                            items.indexOf(list[index].content),
                                            items
                                        ) { _, hint ->
                                            list[index].content = hint
                                            view.text = hint
                                        }
                                    }
                                    "type_firm" -> {
                                        showListDialog(
                                            "规上企业", "规下企业"
                                        ) { _, hint ->
                                            list[index].content = hint
                                            view.text = hint
                                        }
                                    }
                                    "safe_kind" -> {
                                        showListDialog(
                                            "工业", "农林牧渔", "服务业", "危险品业", "娱乐业", "其他"
                                        ) { _, hint ->
                                            list[index].content = hint
                                            view.text = hint
                                        }
                                    }
                                    "type_fire" -> {
                                        showListDialog(
                                            "商场", "市场", "娱乐场所", "重点单位", "其他"
                                        ) { _, hint ->
                                            list[index].content = hint
                                            view.text = hint
                                        }
                                    }
                                    "school_kind" -> {
                                        showListDialog(
                                            "公办", "民办", "其他"
                                        ) { _, hint ->
                                            list[index].content = hint
                                            view.text = hint
                                        }
                                    }
                                    "type_school" -> {
                                        showListDialog(
                                            "小学", "幼儿园", "托管机构", "中学", "大专院校", "职业学校", "其他"
                                        ) { _, hint ->
                                            list[index].content = hint
                                            view.text = hint
                                        }
                                    }
                                    "type_key" -> {
                                        val items = listOf(
                                            "党委", "政府", "档案局", "军分区办公地点和武警部队", "看守所",
                                            "加油站", "电视台", "广播站", "警务室", "加油站", "水源地", "其他"
                                        )
                                        showItemDialog(
                                            list[index].hintText,
                                            items.indexOf(list[index].content),
                                            items
                                        ) { _, hint ->
                                            list[index].content = hint
                                            view.text = hint
                                        }
                                    }
                                    "type_bank" -> {
                                        showListDialog(
                                            "人民银行", "农业银行", "建设银行", "农发行",
                                            "农村信用联社", "自助存取款机", "自助缴费设施", "其他"
                                        ) { _, hint ->
                                            list[index].content = hint
                                            view.text = hint
                                        }
                                    }
                                    "type_other" -> {
                                        showListDialog(
                                            "个体诊所", "电镀", "煤气点", "其他"
                                        ) { _, hint ->
                                            list[index].content = hint
                                            view.text = hint
                                        }
                                    }
                                }
                            }
                        )
                    )
                }
                "input1" -> {
                    add_container.addView(
                        createStableInputView(
                            isRequired = data.isRequired,
                            title = data.title,
                            hintText = data.hintText,
                            type = data.type,
                            length = data.length,
                            digits = data.digits,
                            position = position,
                            content = data.content,
                            listener = { value, _ -> data.input = value }
                        )
                    )
                }
                "input2" -> {
                    add_container.addView(
                        createVariableInputView(
                            isRequired = data.isRequired,
                            title = data.title,
                            hintText = data.hintText,
                            position = position,
                            content = data.content,
                            listener = { value, _ -> data.input = value }
                        )
                    )
                }
            }
        }

        add_container.addView(inflate(R.layout.include_layout_map))
    }

    private fun clearSelectValue(index: Int) {
        val view = add_container.getChildAt(index)
        val innerView = view.findViewById<TextView>(R.id.select_tag)
        innerView.text = ""
        list[index].content = ""
        list[index].secondValue = ""
    }

    private fun initMapView() {
        house_map.apply {
            //隐藏百度Logo
            getChildAt(1).invisible()
            //隐藏缩放控件
            showZoomControls(false)
            //隐藏比例尺
            showScaleControl(false)
            map.apply {
                //普通地图
                mapType = BaiduMap.MAP_TYPE_NORMAL
                //开启定位图层
                isMyLocationEnabled = true
                //隐藏指南针
                uiSettings.isCompassEnabled = false
                //是否启用地图俯视功能
                uiSettings.isOverlookingGesturesEnabled = false

                setMyLocationConfiguration(
                    MyLocationConfiguration(
                        MyLocationConfiguration.LocationMode.NORMAL,
                        false,
                        null
                    )
                )

                setOnMapTouchListener {
                    house_scroll.requestDisallowInterceptTouchEvent(it.action != MotionEvent.ACTION_UP)
                }

                setMapStatusChangeListener {
                    onMapStatusChangeFinish {
                        mLat = it.target.latitude.toString()
                        mLng = it.target.longitude.toString()
                        house_center.startJumpAnimator(60f, 500)
                    }
                }
            }
        }

        if (mData != null) {
            val latitude = mLat.toNotDouble()
            val longitude = mLng.toNotDouble()

            house_map.map.apply {
                setMyLocationData(
                    MyLocationData.Builder()
                        .accuracy(0f)         //精度圈半径
                        .latitude(latitude)   //纬度
                        .longitude(longitude) //经度
                        .build()
                )

                animateMapStatus(
                    MapStatusUpdateFactory.newMapStatus(
                        MapStatus.Builder()
                            .target(LatLng(latitude, longitude))
                            .zoom(18f)
                            .build()
                    )
                )
            }
        } else {
            BDLocationHelper.getInstance(baseContext)
                .startLocation(100) { location, isDone, codes ->
                    if (100 in codes) {
                        if (isDone) {
                            house_map.map.apply {
                                setMyLocationData(
                                    MyLocationData.Builder()
                                        .accuracy(0f)                  //精度圈半径
                                        .direction(location.direction) //方向
                                        .latitude(location.latitude)   //纬度
                                        .longitude(location.longitude) //经度
                                        .build()
                                )

                                animateMapStatus(
                                    MapStatusUpdateFactory.newMapStatus(
                                        MapStatus.Builder()
                                            .target(LatLng(location.latitude, location.longitude))
                                            .zoom(18f)
                                            .build()
                                    )
                                )
                            }
                        } else {
                            toast("位置信息获取失败，请检查网络！")
                        }
                    }
                }
        }
    }

    private fun initListener() {
        tvRight?.oneClick {
            list.forEach {
                when (it.viewFlag) {
                    "select" -> {
                        if (it.isRequired
                            && it.content.isEmpty()
                        ) {
                            toast(it.hintText)
                            return@oneClick
                        }
                    }
                    "input1", "input2" -> {
                        if (it.isRequired && it.input.isEmpty()) {
                            toast(it.hintText)
                            return@oneClick
                        }

                        when (it.inputCheck) {
                            "credit" -> {
                                if (it.input.isNotEmpty()
                                    && !CommonUtil.IDCardValidate(it.input)
                                ) {
                                    toast(it.checkHint)
                                    return@oneClick
                                }
                            }
                            "phone" -> {
                                if (it.input.isNotEmpty()
                                    && !it.input.isMobile()
                                ) {
                                    toast(it.checkHint)
                                    return@oneClick
                                }
                            }
                            "tel" -> {
                                if (it.input.isNotEmpty()
                                    && !it.input.isTel()
                                ) {
                                    toast(it.checkHint)
                                    return@oneClick
                                }
                            }
                            "email" -> {
                                if (it.input.isNotEmpty()
                                    && !it.input.isEmail()
                                ) {
                                    toast(it.checkHint)
                                    return@oneClick
                                }
                            }
                        }
                    }
                }
            }

            if (mLat.isEmpty()
                || mLng.isEmpty()
            ) {
                toast("请选择当前所在位置！")
                return@oneClick
            }

            val param = HashMap<String, Any>()
            param["lat"] = mLat
            param["lng"] = mLng
            param["houseType"] = mValue
            param["houseTypeName"] = mLabel

            list.forEach {
                if (it.viewFlag == "select") {
                    param[it.contentKey] = it.content
                    if (it.secondKey.isNotEmpty()) {
                        param[it.secondKey] = it.secondValue
                    }
                } else {
                    when (it.contentKey) {
                        "cellName" -> {
                            val item = list.first { inner -> inner.action == "build" }
                            if (item.secondValue.isEmpty()) {
                                param[it.contentKey] = ""
                            } else {
                                param[it.contentKey] = it.input
                            }
                        }
                        "floorName" -> {
                            val item = list.first { inner -> inner.action == "build" }
                            if (item.secondValue.isEmpty()) {
                                param[it.contentKey] = ""
                            } else {
                                param[it.contentKey] = it.input
                            }
                        }
                        "roomName" -> {
                            val item = list.first { inner -> inner.action == "build" }
                            if (item.secondValue.isEmpty()) {
                                param[it.contentKey] = ""
                            } else {
                                param[it.contentKey] = it.input
                            }
                        }
                        else -> param[it.contentKey] = it.input
                    }
                }
            }

            if (mData != null) {
                param["id"] = mData?.id.orEmpty()
                getViewModel().getUpdateData(param)
                    .bindLifeCycle(getLifecycleOwner())
                    .subscribeByNoError(
                        event = getViewModel(),
                        onSuccess = {
                            toast("房屋信息修改成功！")

                            val json = JsonUtil.getMapperInstance().writeValueAsString(mData)
                            val obj = JSONObject(json).apply {
                                put("id", mData?.id.orEmpty())
                                put("lat", mLat)
                                put("lng", mLng)
                                list.forEach {
                                    if (it.viewFlag == "select") {
                                        put(it.contentKey, it.content)
                                        if (it.secondValue.isNotEmpty()) {
                                            put(it.secondKey, it.secondValue)
                                        }
                                    } else {
                                        put(it.contentKey, it.input)
                                    }
                                }
                            }
                            LiveEventBus.get("house_edit").post(obj.toString())
                            LiveEventBus.get("house_state").post("done")
                            ActivityStack.screenManager.popActivities(this@HouseAddActivity::class.java)
                        }
                    )
            } else {
                getViewModel().getAddData(param)
                    .bindLifeCycle(getLifecycleOwner())
                    .subscribeByNoError(
                        event = getViewModel(),
                        onSuccess = {
                            toast("添加房屋成功！")
                            ActivityStack.screenManager.popActivities(
                                this@HouseAddActivity::class.java,
                                HouseSelectActivity::class.java
                            )
                        }
                    )
            }
        }
    }

    override fun onResume() {
        super.onResume()
        house_map.onResume()
    }

    override fun onPause() {
        super.onPause()
        house_map.onPause()
    }

    override fun onDestroy() {
        super.onDestroy()
        BDLocationHelper.getInstance(baseContext).stopLocation()
        BDLocationHelper.getInstance(baseContext).removeCode(100)
        house_map.map.isMyLocationEnabled = false
        house_map.onDestroy()
    }

}
